import dayjs from "dayjs"
import {
	nav,
	transTree
} from "@/utils"
import {
	getCommonFormConfig,
	orderDetailSumit,
	getOrderDetail
} from "@/api"
import {
	appConfig
} from "@/config"
export default {
	data() {
		return {
			partsTypeList: [{
					label: "公司配件",
					value: 1
				},
				{
					label: "采购配件",
					value: 2
				},
				{
					label: "个人配件",
					value: 3
				},
			],
			partsType: 1,
			entryList: [],
			show: false,
			showMore: false,
			selectDate: '',
			orderId: "",
			orderInfo: {},
			// 配件list
			allPartsList: [],
			// 带回配件
			backPartsList: [{
				value: "",
				name: "",
				quantity: 1,
				price: ""
			}],
			// 发票信息
			invoiceInfo: {
				remarks: "",
				price: ""
			},
			// 历史发票
			invoiceHistoryList: [],
			columns: [],
			procureColumns: [],
			formConfig: {},
			showParts: false,
			showProcureParts: false,
			// 当前选择的配件类型
			currentParts: {
				index: 0,
				type: 0
			},
			// 客户类型
			customType: "",
			// 评价
			evaluate: "",
			evaluateImage: [],
			echoEvaluateImage: [],
			currentBackPartsIndex: 0,
			showBackParts: false,
			// 采购图片
			procureImage: [],
			// 历史发票
			showInvoice: false,
			// 是否开票
			isInvoice: false,
			minDate: Date.now(),
			// 广告图
			advImage: [],
			echoAdvImage: [],
			isHp: false,
			isCost: false,
			isBack: false,
			isAdv: false,
			showAdvTip: false,
			showClearTip: false,
			// 广告图备注
			ggRemarks: '',
			// 服务内容
			repair_status: ''
		}
	},
	computed: {
		// 总成本 = 单费 + 配件费用 + 带回配件费用 + 税费
		finalCost() {
			// 配件成本
			const partsCost = this.allPartsList.reduce((acc, item) => acc += item.quantity * item.price, 0)
			// 带回成本
			const backPartsCost = this.backPartsList.reduce((acc, item) => acc += item.quantity * item.price, 0)
			// 税费
			// const taxation = this.invoiceInfo.price * appConfig.taxation

			return partsCost + backPartsCost
		},
		// 税费
		tax() {
			const price = this.formConfig.tax * this.invoiceInfo.price;
			if (isNaN(price) || price <= 0) return ""
			return price
		},
		showProcureUpload() {
			return this.allPartsList.some(item => item.type == 2)
		}
	},
	methods: {
		toPage(index) {
			const data = this.entryList[index]
			if (!data.url && data.type === 'more') {
				this.showMore = true
				return;
			}
			this.nav(`${data.url}?id=${this.orderId}`)
		},
		confirm(e) {
			console.log(e)
			this.show = false;
			this.selectDate = dayjs(e.value).format("YYYY-MM-DD")
		},
		// 选择发票
		confirmInvoice(e) {
			console.log(e)
			this.invoiceInfo.remarks = e.value[0].value
			this.showInvoice = false
		},
		// 选择配件
		selectParts(type, index) {
			this.partsType = type
			this.currentParts = {
				index,
				type
			}
			const pickerRef = this.$refs.uPicker
			if (type == 1) {
				this.showParts = true
				this.columns = [this.formConfig.partsCompanyList]
			} else if (type == 3) {
				this.showParts = true
				this.columns = [this.formConfig.partsPersonList]
			} else {
				this.showParts = true
				this.columns = [this.formConfig.partsPurchaseTypeList]
			}
		},
		// 删除配件信息
		deleteParts(index) {
			console.log(index)
			this.allPartsList.splice(index, 1)
		},
		// 添加配件信息
		addParts(type) {
			let tpl = {
				id: "",
				name: "",
				quantity: "1",
				price: "",
				type,
				// 自定义配件名称
				customName: ""
			}
			this.$set(this.allPartsList, this.allPartsList.length, tpl)
		},
		confrimParts(e) {
			const {
				type,
				index
			} = this.currentParts
			let value = e.value[0]
			if (e.value.length > 1) {
				value = e.value[1]
			}
			this.allPartsList[index].name = value.name
			this.allPartsList[index].quantity = 1
			this.allPartsList[index].id = value.value
			this.allPartsList[index].price = value.price ?? 0
			this.allPartsList[index].purchaseType = value.type
			this.allPartsList[index].customName = this.allPartsList[index].customName || value.name
			this.showParts = false
			this.showProcureParts = false
		},
		// 二级选择
		changeHandler(e) {
			const pickerRef = this.$refs.uPicker
			if (e.columnIndex === 0) {
				if (this.procureColumns[0][e.index].children) {
					const tree = transTree(this.formConfig.partsPurchaseTypeList)
					// console.log(tree)
					this.$set(this.procureColumns, 1, this.procureColumns[0][e.index].children)
					// pickerRef.setColumnValues(1, tree[e.index].children)
				}
			}
		},

		// 选择带回配件
		selectBackParts(index) {
			this.showBackParts = true
			this.currentBackPartsIndex = index
		},
		// 删除带回配件
		deleteBackParts(index) {
			this.backPartsList.splice(index, 1)
		},
		// 添加带回配件
		addBackParts() {
			let tpl = {
				value: "",
				name: "",
				quantity: 1,
				price: "",
				// 自定义名称
				customName: ""
			}
			this.$set(this.backPartsList, this.backPartsList.length, tpl)
		},
		confrimBackParts(e) {
			let value = e.value[0]
			let index = this.currentBackPartsIndex
			this.backPartsList[index].value = value.value
			this.backPartsList[index].name = value.name
			this.backPartsList[index].quantity = 1
			this.backPartsList[index].price = value.price
			this.backPartsList[index].customName = value.customName || value.value
			this.showBackParts = false

		},
		// 获取配件
		getFormConfig(type) {
			return getCommonFormConfig(this.orderId).then(res => {
				console.log(res, '获取配件')
				const {
					code,
					data
				} = res;
				if (code !== 1) return;
				this.formConfig = data
			})
		},
		/**
		 * 提交详情参数格式化
		 * @param {Object} type repair 返修
		 */
		formatParams(type) {
			const {
				remarks,
				price
			} = this.invoiceInfo
			const companyParts = this.allPartsList.filter(item => item.type == 1)
			const purchaseParts = this.allPartsList.filter(item => item.type == 2)
			const personParts = this.allPartsList.filter(item => item.type == 3)
			const some = this.allPartsList.some(item => item.quantity === '' || isNaN(Number(item.quantity)))
			const backSome = this.backPartsList.some(item => item.quantity === '' || isNaN(Number(item.quantity)))
			if (this.orderInfo.repair_status === '') {
				this.toast("请选择服务内容")
				return false
			}
			if (some) {
				this.toast("请输入正确配件数量")
				return false
			}
			if (backSome) {
				this.toast("请输入正确的带回配件数量")
				return false
			}
			// 存在采购配件是必须上传图片
			if (purchaseParts.length > 0 && this.procureImage.length === 0) {
				this.toast("请上传采购图片")
				return false;
			}
			if (type !== 'repair') {
				// 发票
				if (this.isInvoice) {
					if (!remarks) {
						this.toast("发票内容不能为空")
						return false;
					}
					if (!price) {
						this.toast("请输入发票金额")
						return false;
					}
				}
				// 存在好评时，必须上传好评图片
				// if (this.evaluate && this.evaluateImage.length === 0) {
				// 	this.toast("请上传好评截图")
				// 	return false;
				// }
				if (!this.evaluate && this.evaluateImage.length > 0) {
					this.toast("请选择好评类型")
					return false;
				}
				if (!this.customType) {
					this.toast("请选择客户标签")
					return false
				}
				if (this.advImage.length === 0 && !this.ggRemarks) {
					this.showAdvTip = true
					return false
				}
				if (this.isHp && (this.orderInfo.praise_list.some(o => o.images_list.length == 0 || o.praise_type ==
						''))) {
					this.toast("请选择选项和上传图片")
					return false
				}

			}
			return {
				// 订单ID
				realorder_id: this.orderId,
				// 公司配件ID
				company: companyParts.map(it => {
					return {
						parts_person_id: it.id,
						number: it.quantity
					}
				}),
				// 个人配件
				person: personParts.map(it => {
					return {
						parts_person_id: it.id,
						number: it.quantity
					}
				}),
				// 采购配件
				purchase: purchaseParts.map(it => {
					return {
						type: it.purchaseType || "",
						content: it.customName,
						price: it.price,
						number: it.quantity
					}
				}),
				// 保修日期
				warranty_date: this.selectDate,
				// 好评类型
				is_praise: this.evaluate,
				// 发票内容
				invoice_content: this.invoiceInfo.remarks,
				//税费
				postage: this.invoiceInfo.price * this.formConfig.tax,
				// 好评
				hp_img: this.evaluateImage.map(item => item.url),
				// 广告图
				gg_img: this.advImage.map(item => item.url)[0] || "",
				// 广告图备注
				gg_remarks: this.ggRemarks,
				// 配件报销
				purchase_images: this.procureImage.map(item => item.url),
				// 带回配件
				takeback: this.backPartsList.reduce((arr, item) => {
					// 过滤只选择了配件类型的数据
					if (item.value) {
						arr.push({
							takeback_parts_type: item.value,
							takeback_parts_name: item.customName,
							takeback_number: item.quantity,
							takeback_parts_price: item.price || ""
						})
					}
					return arr
				}, []),
				utype_tags: this.customType,
				repair_status: this.orderInfo.repair_status,
				praise: this.isHp ? this.orderInfo.praise_list.map(o => (o.images = o.images_list, {
					images: o.images,
					praise_type: o.praise_type,
					platform: o.platform
				})) : []
			}
		},
		// 订单详情
		getDetail() {
			return getOrderDetail(this.orderId).then(res => {
				const {
					data,
					code
				} = res;
				this.orderInfo = data;
				this.paymentList = (data.payment || []).map(item => {
					return {
						paytype: item.paytype,
						payprice: item.payprice
					}
				})
				if (this.orderInfo.praise_list.length === 0) {
					this.orderInfo.praise_list.push({
						platform: '大众',
						images: [],
						praise_type: ''
					})
				}
				this.entryList = [{
						label: "验券",
						icon: "/static/image/yanquan.png",
						url: '/subpackage/order/pages/check-ticket/index',
						visiable: data.powerStatus.postPayment === 1
					},
					{
						label: "支付提交",
						icon: "/static/image/yanquan.png",
						url: '/subpackage/order/pages/payment/index',
						visiable: data.powerStatus.postPayment === 1
					},
					{
						label: "历史记录",
						icon: "/static/image/history.png",
						url: '/subpackage/order/pages/history/index',
						visiable: true
					},
					{
						label: "更多功能",
						icon: "/static/image/more.png",
						url: "",
						type: "more",
						visiable: true
					}
				]
				this.echoData(data)
			})
		},
		// 选择历史发票
		selectHistoryInvoice() {
			if (!this.formConfig.invoiceHistoryList.length) return this.toast("暂无历史发票选择")
			this.showInvoice = true;
		},
		// 数据回显
		echoData(data) {
			const {
				invoice,
				purchase_images,
				warranty_date,
				praise_type_text,
				takeback,
				partsperson,
				utype_tags,
				partscompany,
				gg_img,
				hp_img,
				hp_img_list,
				problem_type,
				problem,
				orderattr
			} = data;
			this.selectDate = warranty_date
			this.problem = problem
			const evaluateFind = this.formConfig.praiseTypeList.find(it => it.name === praise_type_text)
			if (invoice) {
				this.invoiceInfo.remarks = invoice.invoice_content
				this.invoiceInfo.price = invoice.postage
			}
			if (problem_type) {
				this.problem_type = problem_type.split(",")
			}
			if (evaluateFind) {
				this.evaluate = evaluateFind.value
				this.isHp = true
			}
			if (hp_img_list.length > 0) {
				this.echoEvaluateImage = hp_img_list
				this.isHp = true
			}
			if (gg_img) {
				this.echoAdvImage = [gg_img]
				this.isAdv = true
			}
			if (orderattr) {
				this.ggRemarks = orderattr.gg_remarks
			}
			if (takeback && takeback.length > 0) {
				this.isBack = true
				this.backPartsList = takeback.map(item => {
					return {
						value: item.takeback_parts_type,
						name: item.takeback_parts_type,
						quantity: item.takeback_number,
						price: item.takeback_parts_price,
						customName: item.takeback_parts_name,
					}
				})
			}
			this.onRequestd(data)
			// 个人配件
			const p = []
			partsperson.map(item => {
				let list = this.formConfig.partsPersonList
				for (let i = 0; i < list.length; i++) {
					if (item.parts_person_id === list[i].value) {
						p.push({
							id: list[i].value,
							name: list[i].name,
							customName: list[i].name,
							price: list[i].price,
							quantity: item.number,
							type: 3
						})
					}
				}
			})
			// 公司配件
			const c = []
			// 采购
			const cg = []
			partscompany.map(item => {
				let list = this.formConfig.partsCompanyList
				if (item.is_new === 1) {
					cg.push({
						id: item.content,
						name: item.parts_name,
						customName: item.parts_name,
						price: item.price,
						quantity: 1,
						type: 2
					})
				}
				for (let i = 0; i < list.length; i++) {
					if (item.parts_person_id === list[i].value) {
						c.push({
							id: list[i].value,
							name: list[i].name,
							customName: list[i].name,
							price: list[i].price,
							quantity: item.number,
							type: 1
						})
					}
				}
			})

			this.allPartsList = [...p, ...c, ...cg]
			this.isCost = this.allPartsList.length > 0
			this.customType = utype_tags || ""
			// this.isInvoice = this.formConfig.invoiceHistoryList && this.formConfig.invoiceHistoryList.length

			this.isInvoice = this.orderInfo.invoice ? true : false

			// backPartsList: [
			// 	{ value: "", name: "", quantity: 1, price: 0 }
			// ],
		},
		onRequestd() {},
		hpUpload(e) {
			console.log(e)
			this.evaluateImage = e
		},
		ggUpload(e) {
			console.log(e, '--111-')
			this.advImage = e
		},
		formatter(type, value) {
			if (type === 'year') {
				return `${value}年`
			}
			if (type === 'month') {
				return `${value}月`
			}
			if (type === 'day') {
				return `${value}日`
			}
			return value
		},
		// 选择好评
		selectEvaluate(e) {
			if (this.evaluate === e) {
				this.evaluate = ""
				return
			}
			this.evaluate = e
		},
		// 清空带回配件
		clearBackParts() {
			this.backPartsList = [{
				value: "",
				name: "",
				quantity: 1,
				price: ""
			}]
			this.showClearTip = false
		},
		submit() {
			const formData = this.formatParams()
			if (!formData) return;
			// return;
			orderDetailSumit(formData).then(res => {
				if (res.code === 1) {
					this.toast("提交成功")
					setTimeout(() => {
						this.back()
						uni.$emit('changeList')
					}, 1000)
				}
			})
		},
		async init() {
			await this.getFormConfig()
			await this.getDetail()
		}
	}
}